<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\common\model\GiftActivity;
use app\common\model\GiftIssuer;
use app\admin\model\Upload;
 
class ClearGiftImg extends Command
{
	
    protected function configure(){
        $this->setName('ClearGiftImg')->setDescription('清空超过90天的礼品图片');
    }
 
    protected function execute(Input $input, Output $output){
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/
        $this->change_income($output);
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }
	
    private function change_income($output){
    	
		// 获取90天前的活动id
		$date = date("Y-m-d", time() - 90*24*60*60 );
		$activityIds = GiftActivity::where("stop_time",'<', $date)->column('id');
		
		// 可删除数量为0时，不执行删除动作
		if(count($activityIds) < 1){
			$output->writeln('fail--0');
			return fasle;
		}
		
		// 获取90天前的图片路径
		$guids = array_unique(GiftIssuer::where("activity_id",'in',$activityIds)->column('guid'));
		$filePaths = Upload::where("file_guid",'in',$guids)
			->where('file_type','礼品凭证')
			->where("file_buss_type","礼品")
			->column('file_path');
		
			
		//删除文件数据
		$result = Upload::where("file_path",'in',$filePaths)->delete();
		
		if($result == 0){
			
			Db::name('system_log')->insert([
				'url' =>'定时任务-清空超过90天的礼品图片', 
				'result'=>'失败：本次共删除0张图片！'
			]);
			$output->writeln('fail--0');
			return fasle;
			
		}else{
			
			//删除物理文件
			foreach ($filePaths as $path){ @unlink($path); }
			
			//添加日志
			Db::name('system_log')->insert([
				'url' =>'定时任务-清空超过90天的礼品图片', 
				'result'=>'成功：本次共删除'.count($filePaths).'张图片！'
			]);
			
			//控制台通知
			$output->writeln('success--'.count($filePaths));
		}
		
    }
	
}